package com.github.base.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.json.JSONUtil;
import cn.idev.excel.FastExcel;
import cn.idev.excel.annotation.ExcelProperty;
import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.read.listener.ReadListener;
import com.github.base.mapper.LogMapper;
import com.github.base.utils.Result;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileReader;
import java.io.FileWriter;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @program: anti-fraud
 * @description:
 * @author: hui.zhang
 * @date: 2021/1/22 2:34 下午
 **/

@Slf4j
@RestController
@Tag(name = "测试")
@RequiredArgsConstructor
public class HomeController {
    private final LogMapper logMapper;


    @GetMapping("/")
    @Operation(summary = "测试")
    public String home() {
        return "如果看到这句话，证明部署已经成功了。恭喜～～～";
    }

    @GetMapping("/testDataScope")
    @Operation(summary = "测试数据拦截")
    public Result<List<Map>> testDataScope() {
        List<Map> all = logMapper.findAll();
        return Result.ok(all);
    }

    @SaIgnore
    @GetMapping("/testExcel")
    @Operation(summary = "测试excel")
    public Result<?> testExcel() {
        String file = "/Users/jzy/Desktop/03-8月支付宝底稿【支付宝后台】.xlsx";
        // 直接读取为 Map 列表
//        FastExcel.read(file, HashMap.class, new PageReadListener<>(dataList -> {
//            // 分页批量处理
//            log.info("读取到一批数据: {}", JSONUtil.toJsonStr(dataList));
//            // TODO: 实现数据处理逻辑
//        }))
//        .sheet()
//        .doRead();

        // 处理读取的数据列表
//        for (Map<Integer, String> data : list) {
//            log.info("读取到的数据: {}", JSONUtil.toJsonStr(data));
//        }

        FastExcel.read(file, DemoData.class, new DemoDataListener()).sheet().doRead();
        return Result.ok();
    }

    // 实现 ReadListener 接口，设置读取数据的操作
    public class DemoDataListener implements ReadListener<DemoData> {
        @Override
        public void invoke(DemoData data, AnalysisContext context) {
            System.out.println("解析到一条数据" + JSONUtil.toJsonStr(data));
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            System.out.println("所有数据解析完成！");
        }
    }

    @Data
    public static class DemoData {
        @ExcelProperty(index = 0)
        private String a;
        @ExcelProperty(index = 1)
        private String b;
        @ExcelProperty(index = 2)
        private String c;
        @ExcelProperty(index = 3)
        private LocalDateTime d;
    }

    @SaIgnore
    @GetMapping("/testCsv")
    public Result<?> testCsv() throws Exception {
        int rowsPerFile = 5000; // 每个小文件包含的行数
        String filePath = "/Users/jzy/Desktop/20887419370593460156_202410_账务明细.csv";
        String outputFilePrefix = "/Users/jzy/Desktop/csv/output_file_";
        try (CSVReader reader = new CSVReader(new FileReader(filePath))) {
            String[] line;
            int fileCounter = 0;
            int rowCount = 0;
            CSVWriter writer = null;

            while ((line = reader.readNext()) != null) {
                if (rowCount % rowsPerFile == 0) {
                    if (writer != null) {
                        writer.close();
                    }
                    fileCounter++;
                    String outputFilePath = outputFilePrefix + fileCounter + ".csv";
                    writer = new CSVWriter(new FileWriter(outputFilePath));
                    if (rowCount == 0) {
                        writer.writeNext(line);
                    }
                }
                writer.writeNext(line);
                rowCount++;
            }

            if (writer != null) {
                writer.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok();
    }

}
